package com.buba.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.buba.mapper.*;
import entity.sparemanage.*;
import com.buba.mapper.SpareTypesMapper;
import entity.sparemanage.SpareLedger;
import com.buba.mapper.SpareLedgerMapper;
import com.buba.service.SpareLedgerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import entity.sparemanage.dto.*;
import entity.system.CodeRules;
import feign.systemFeign;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import entity.sparemanage.dto.SpareLedgerDto;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import utils.PageResult;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import utils.pageutil.MyPageHelper;
import utils.pageutil.PageRequest;

/**
 * <p>
 * 备件台账 服务实现类
 * </p>
 *
 * @author beisheng
 * @since 2023-05-18
 */
@Service
public class SpareLedgerServiceImpl extends ServiceImpl<SpareLedgerMapper, SpareLedger> implements SpareLedgerService {

    @Autowired
    private SpareLedgerMapper spareLedgerMapper;

    @Autowired
    private SpareTypesMapper spareTypesMapper;

    @Autowired
    private ImageMapper imageMapper;

    @Autowired
    private FileMapper fileMapper;

    @Autowired
    private systemFeign systemFeign;

    @Autowired
    private SpareDeviceMapper spareDeviceMapper;
    /* *
     * @Author: beisheng
     * @Descriprion: 备件台账列表
     * @Date: 2023/5/19 8:47
     * @Return: common.R
     * @Param: [spareLedger, pagesDto]
     */

    @Override
    public PageResult selAllSpareLedger(SpareLedgerDto spareLedger) {

        SpareQueryWrapperDto spareQueryWrapperDto = new SpareQueryWrapperDto();
        QueryWrapper<SpareLedger> queryWrapper = spareQueryWrapperDto.determine(spareLedger);
        Page<SpareLedger> page = new Page<>(spareLedger.getPage(),spareLedger.getPageSize());
        Page<SpareLedger> spareLedgerPage = spareLedgerMapper.selectPage(page, queryWrapper);
        List<SpareLedger> ledgerList = spareLedgerMapper.selectList(new QueryWrapper<SpareLedger>().eq("delete_flag", 0));
        List<SpareLedger> records = spareLedgerPage.getRecords();
        for (SpareLedger record : records) {
            SpareTypes spareTypes = spareTypesMapper.selectOne(new QueryWrapper<SpareTypes>().eq("delete_flag", 0).eq("sp_id", record.getSpTypeId()));
            record.setSpTypeName(spareTypes.getSpTypename());
            record.setDiffer(record.getUpperInventory()-record.getTotalInventory());
        }
        return new PageResult(spareLedger.getPage(),spareLedger.getPageSize(),ledgerList.size(),records);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(addSpareLedgerDto add) {
        //1.查询编码生成规则，进行生成编码
        CodeRules bj = systemFeign.selAllRules("BJ");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(bj.getDateTime());
        String format = simpleDateFormat.format(new Date());
        List<SpareLedger> spareLedgerList = spareLedgerMapper.selectList(new QueryWrapper<SpareLedger>().eq("delete_flag", 0));
        String code = bj.getPrefix()+format+"0"+(spareLedgerList.size()+1);
        //2.添加数据到备件表
        SpareLedger spareLedger = new SpareLedger();
        BeanUtils.copyProperties(add,spareLedger);
        spareLedger.setSpCode(code);
        spareLedger.setTotalInventory(0);
        spareLedger.setAmountInventory(0.0);
        spareLedger.setReplaceCycle(add.getCycle()+add.getCycleUnit());
        spareLedger.setOperator("张三");
        spareLedger.setUpperInventory(Integer.valueOf(add.getUpperInventory()));
        spareLedger.setLowerInventory(Integer.valueOf(add.getLowerInventory()));
        spareLedger.setSaRemark(add.getRemark());
        spareLedger.setSpTypeId(add.getSpTypeId().get(0));
        spareLedger.setCreateTime(new Date());
        spareLedger.setUpdateTime(new Date());
        spareLedger.setDeleteFlag(0);
        //3.如果有关联设备，那么上传到关联设备表
        List<SpareDevice> associations = add.getAssociation();
        try {
            spareLedgerMapper.insert(spareLedger);
            // 执行其他操作
        } catch (Exception e) {
            // 发生异常，手动回滚事务
            throw new RuntimeException("新增备件失败", e);
        }
        if (associations!=null){
            for (SpareDevice association : associations) {
                association.setCreateTime(new Date());
                association.setUpdateTime(new Date());
                association.setDeleteFlag(0);
                association.setArchivesId(spareLedger.getSpId());
                try {
                    spareDeviceMapper.insert(association);
                    // 执行其他操作
                } catch (Exception e) {
                    // 发生异常，手动回滚事务
                    throw new RuntimeException("新增备件关联设备失败", e);
                }
            }
        }
        //4.如果有备件图片，那么上传到图片表
        List<imgList> imgLists = add.getImgList();
        if (imgLists!=null){
            for (imgList imgList : imgLists) {
                Image image = new Image();
                image.setAssociationId(spareLedger.getSpId());
                image.setImageAddress(imgList.getUrl());
                image.setImageType(1);
                image.setCreateTime(new Date());
                image.setUpdateTime(new Date());
                image.setDeleteFlag(0);
                try {
                    imageMapper.insert(image);
                }catch (Exception e){
                    throw new RuntimeException("图片新增失败",e);
                }
            }
        }
        //5.如果有关联文档，那么上传到文件表
        List<fileList> fileLists = add.getFileList();
        if (fileLists!=null){
            for (fileList fileList : fileLists) {
                File file = new File();
                file.setAssociationId(spareLedger.getSpId());
                file.setFileAddress(fileList.getUrl());
                file.setFileName(fileList.getName());
                file.setFileType(1);
                file.setCreateTime(new Date());
                file.setUpdateTime(new Date());
                file.setDeleteFlag(0);
                try {
                    fileMapper.insert(file);
                }catch (Exception e){
                    throw new RuntimeException("文件新增失败",e);
                }
            }
        }
    }

    /* *
     * @Author: beisheng
     * @Descriprion: 备件单查
     * @Date: 2023/5/24 8:51
     * @Return: common.R
     * @Param: [id]
     */

    @Override
    public addSpareLedgerDto selOneToSpare(Integer id) {
        addSpareLedgerDto addSpareLedgerDto = new addSpareLedgerDto();
        //1.根据备件ID查询备件详情
        SpareLedger spareLedger = spareLedgerMapper.selectOne(new QueryWrapper<SpareLedger>().eq("sp_id", id).eq("delete_flag", 0));
        BeanUtils.copyProperties(spareLedger,addSpareLedgerDto);
        addSpareLedgerDto.setRemark(spareLedger.getSaRemark());
        addSpareLedgerDto.setUpperInventory(String.valueOf(spareLedger.getUpperInventory()));
        addSpareLedgerDto.setLowerInventory(String.valueOf(spareLedger.getLowerInventory()));
        addSpareLedgerDto.setCycle(spareLedger.getReplaceCycle().substring(0,spareLedger.getReplaceCycle().length()-1));
        addSpareLedgerDto.setCycleUnit(spareLedger.getReplaceCycle().substring((spareLedger.getReplaceCycle().length()-1),spareLedger.getReplaceCycle().length()));
        List<Integer> list = new ArrayList<>();
        list.add(spareLedger.getSpTypeId());
        addSpareLedgerDto.setSpTypeId(list);
        //2.查询备件关联设备信息
        List<SpareDevice> spareDevices = spareDeviceMapper.selectList(new QueryWrapper<SpareDevice>().eq("archives_id", id).eq("delete_flag", 0));
        addSpareLedgerDto.setAssociation(spareDevices);
        //3.查询备件关联图片
        List<Image> imageList = imageMapper.selectList(new QueryWrapper<Image>().eq("association_id", id).eq("image_type", 1).eq("delete_flag", 0));
        List<imgList> imgLists = new ArrayList<>();
        for (Image image : imageList) {
            imgList imgList = new imgList();
            imgList.setName(image.getImageAddress());
            imgList.setUrl(image.getImageAddress());
            imgLists.add(imgList);
        }
        addSpareLedgerDto.setImgList(imgLists);
        //4.查询备件关联文档
        List<File> fileList = fileMapper.selectList(new QueryWrapper<File>().eq("association_id", id).eq("file_type", 1).eq("delete_flag", 0));
        List<fileList> fileLists = new ArrayList<>();
        for (File file : fileList) {
            fileList fileList1 = new fileList();
            fileList1.setName(file.getFileName());
            fileList1.setUrl(file.getFileAddress());
            fileLists.add(fileList1);
        }
        addSpareLedgerDto.setFileList(fileLists);
        return addSpareLedgerDto;
    }

    /* *
     * @Author: beisheng
     * @Descriprion: 修改备件信息
     * @Date: 2023/5/24 14:06
     * @Return: common.R
     * @Param: [updates]
     */

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateSpareLedger(addSpareLedgerDto updates) {

        SpareLedger spareLedger = new SpareLedger();
        BeanUtils.copyProperties(updates,spareLedger);
        spareLedger.setUpdateTime(new Date());
        try {
            spareLedgerMapper.updateById(spareLedger);
        }catch (Exception e){
            throw new RuntimeException("修改备件基本信息失败",e);
        }


        try {
            imageMapper.delete(new QueryWrapper<Image>().eq("association_id",updates.getSpId()).eq("image_type",1));
        }catch (Exception e){
            throw new RuntimeException("删除图片失败",e);
        }

        try {
            fileMapper.delete(new QueryWrapper<File>().eq("association_id",updates.getSpId()).eq("file_type",1));
        }catch (Exception e){
            throw new RuntimeException("删除文件失败",e);
        }


        //4.如果有备件图片，那么上传到图片表
        List<imgList> imgLists = updates.getImgList();
        if (imgLists!=null){
            for (imgList imgList : imgLists) {
                Image image = new Image();
                image.setAssociationId(spareLedger.getSpId());
                image.setImageAddress(imgList.getUrl());
                image.setImageType(1);
                image.setCreateTime(new Date());
                image.setUpdateTime(new Date());
                image.setDeleteFlag(0);
                try {
                    imageMapper.insert(image);
                }catch (Exception e){
                    throw new RuntimeException("图片新增失败",e);
                }
            }
        }
        //5.如果有关联文档，那么上传到文件表
        List<fileList> fileLists = updates.getFileList();
        if (fileLists!=null){
            for (fileList fileList : fileLists) {
                File file = new File();
                file.setAssociationId(spareLedger.getSpId());
                file.setFileAddress(fileList.getUrl());
                file.setFileName(fileList.getName());
                file.setFileType(1);
                file.setCreateTime(new Date());
                file.setUpdateTime(new Date());
                file.setDeleteFlag(0);
                try {
                    fileMapper.insert(file);
                }catch (Exception e){
                    throw new RuntimeException("文件新增失败",e);
                }
            }
        }
    }
    /**
     * @return common.R
     * @Author atlong
     * @Description 查询备件列表信息
     * @Date 2023/6/17 10:46
     * @Param [spareLedger]
     **/
    @Override
    public utils.pageutil.PageResult selSpareLedgers(SpareLedgerDto spareLedger) {
        QueryWrapper<SpareLedger> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("delete_flag",0);
        if (spareLedger.getSpCode()!=null){
            queryWrapper.like("sp_code",spareLedger.getSpCode());
        }

        PageRequest pageRequest = new PageRequest(spareLedger.getPage(), spareLedger.getPageSize());
        MyPageHelper.startPage(pageRequest);
        List<SpareLedger> list = spareLedgerMapper.selectList(queryWrapper);

        utils.pageutil.PageResult pageResult = MyPageHelper.getPageResult(list);

        return pageResult;
    }
}
